package com.zly.framework.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.zly.framework.rbac.model.entity.User;
import com.zly.framework.rbac.exception.SystemException;
import com.zly.framework.rbac.mapper.PermissionMapper;
import com.zly.framework.rbac.mapper.UserMapper;
import com.zly.framework.rbac.service.RoleService;
import com.zly.framework.rbac.service.UserRoleService;
import com.zly.framework.rbac.service.UserService;
import jakarta.annotation.Resource;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Collection;
import java.util.List;

@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Resource
    private RoleService roleServiceImpl;
    @Resource
    private UserRoleService userRoleServiceImpl;
    @Resource
    private PermissionMapper permissionMapper;

    @Resource
    private PasswordEncoder passwordEncoder;

    @Override
    @Cacheable(cacheNames = "username", key = "#username")
    public User getUserInfoByUsername(String username) {
        User user = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, username));
        user.setPassword(null);
        user.setRoles(roleServiceImpl.getAllRolesByUserId(user));
        user.setPermissions(permissionMapper.getAllPermissionsByUserId(user));
        return user;
    }



    /**
     * 添加新用户
     *
     * @param user 用户
     */
    @Override
    public void addNewUser(User user) {
        User user1 = baseMapper.selectOne(new LambdaQueryWrapper<User>().eq(User::getUsername, user.getUsername()));
        if (user1 == null) {
            String encode = passwordEncoder.encode(user.getPassword());
            user.setPassword(encode);
            baseMapper.insert(user);
        } else {
            throw new SystemException("用户名已存在，请重新添加");
        }
    }

    /**
     * 给用户分配角色
     *
     * @param userIds 用户id
     * @param roleIds 角色id
     */
    @Transactional
    @Override
    public void grantRoles(List<Long> userIds, List<Long> roleIds) {
        userRoleServiceImpl.deleteUserRoleByUserIds(userIds);
        userRoleServiceImpl.grantUserRoleByUserIds(userIds, roleIds);
    }
}
